import { useRef, useState } from "react"
import { useParams, useHistory } from "react-router-dom"
import { message, Space, Modal, Table, Tag } from 'antd'
import { ArrowLeftOutlined, CheckOutlined, SaveOutlined } from '@ant-design/icons'
import { saveEditorJson, validateData } from "../../apis/processModel"
import ProcessDesigner from "../../components/ProcessDesigner"
import ModelerSaveModal from "../../components/ModelerSaveModal"
import ToolbarButton from "../../components/ProcessDesigner/components/ToolbarButton"

const ModelerProcessDesign = () => {
  const history = useHistory()
  const designerRef = useRef(null)
  const { id: modelId } = useParams()
  const [validateResult, setValidataResult] = useState(null)
  const [metaData, setMetaData] = useState({})

  const handleBeforeShow = (showAction) => {
    const { modelData } = designerRef.current.getSubmitConfig()
    const metaData = {
      name: modelData.properties.name,
      key: modelData.properties.process_id,
      description: modelData.properties.documentation,
    }
    setMetaData(metaData)
    showAction()
  }

  const handleSave = async (saveValues, callbacks = {}) => {
    try {
      const { name, key, description, newversion, comment } = saveValues
      const {
        modelMetaData,
        modelData,
        successCallBack
      } = designerRef.current.getSubmitConfig()

      const submitData = {
        modeltype: modelMetaData.model.modelType,
        json_xml: JSON.stringify(modelData),
        name, key, description,
        newversion: !!newversion,
        comment: comment || '',
        lastUpdated: modelMetaData.lastUpdated
      };

      const responseData = await saveEditorJson(modelId, submitData)

      message.success('保存成功！')

      callbacks.hideModal && callbacks.hideModal()
      callbacks.clearSending && callbacks.clearSending()

      successCallBack(submitData, responseData)

    } catch (error) {
      callbacks.clearSending && callbacks.clearSending()
      message.error(error.message || '保存失败！')
    }
  }

  const handleValidate = async () => {
    const { modelData } = designerRef.current.getSubmitConfig()
    try {
      const res = await validateData(modelData)
      setValidataResult(res.map((el, i) => ({
        ...el,
        index: i
      })))
    } catch (error) {
      message.error(error.message || '验证失败')
    }
  }

  const renderHeaderButtons = () => {
    return <Space>
      <ToolbarButton onClick={handleValidate}>
        <CheckOutlined style={{ color: '#4b4' }} />
        <span style={{ marginLeft: 5 }}>验证</span>
      </ToolbarButton>
      <ModelerSaveModal
        modelMetaData={metaData}
        onSubmit={handleSave}
        beforeShow={handleBeforeShow}
      >
        <ToolbarButton type="primary">
          <SaveOutlined />
          <span style={{ marginLeft: 5 }}>保存</span>
        </ToolbarButton>
      </ModelerSaveModal>
    </Space>
  }

  return <div className="wh100">
    <ProcessDesigner
      ref={designerRef}
      modelId={modelId}
      toolBarRightSlot={renderHeaderButtons()}
      toolBarLeftSlot={
        <ToolbarButton onClick={() => {
          history.goBack()
        }}>
          <ArrowLeftOutlined />
          <span style={{ marginLeft: 5 }}>返回</span>
        </ToolbarButton>
      }
    ></ProcessDesigner>
    <Modal
      width={720}
      title="验证结果"
      visible={!!validateResult}
      footer={null}
      maskClosable={false}
      keyboard={false}
      onCancel={() => setValidataResult(null)}
    >
      <Table
        dataSource={validateResult || []}
        bordered
        size="small"
        rowKey="index"
        columns={[
          {
            key: 'activityName',
            dataIndex: 'activityName',
            title: 'Name'
          },
          {
            key: 'defaultDescription',
            dataIndex: 'defaultDescription',
            title: 'Description'
          },
          {
            key: 'warning',
            dataIndex: 'warning',
            title: 'Critical',
            width: 100,
            align: 'center',
            render: (text) => {
              return text ? <Tag color="orange">Warning</Tag> : <Tag color="red">Critical</Tag>
            }
          }
        ]}
      ></Table>
    </Modal>
  </div>
}

export default ModelerProcessDesign